package control

import (
	"gvm/instructions/base"
	"gvm/rtda"
)

/*
tableswitch
<0-3 byte pad>
defaultbyte1
defaultbyte2
defaultbyte3
defaultbyte4
lowbyte1
lowbyte2
lowbyte3
lowbyte4
highbyte1
highbyte2
highbyte3
highbyte4
jump offsets...
*/
// Access jump table by index and jump

type TABLE_SWITCH struct {
	defaultOffset int32
	low           int32
	high          int32
	jumpOffsets   []int32
}

func (ts *TABLE_SWITCH) FetchOperands(reader *base.ByteCodeReader) {
	reader.SkipPadding()
	ts.defaultOffset = reader.ReadInt32()
	ts.low = reader.ReadInt32()
	ts.high = reader.ReadInt32()
	jumpOffsetsCount := ts.high - ts.low + 1
	ts.jumpOffsets = reader.ReadInt32s(jumpOffsetsCount)
}

func (ts *TABLE_SWITCH) Execute(jFrame *rtda.JFrame) {
	index := jFrame.OperandStack().PopInt()

	var offset int
	if index >= ts.low && index <= ts.high {
		offset = int(ts.jumpOffsets[index-ts.low])
	} else {
		offset = int(ts.defaultOffset)
	}

	base.Branch(jFrame, offset)
}
